package caozuoxitong;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class RoundRobinScheduler {
    public RoundRobinScheduler() {
    }

    public static void roundRobinSchedule(List<PCB> processes, int timeSlice) {
        List<PCB> finishList = new ArrayList();

        for(int currentTime = 0; !processes.isEmpty(); printProcessInfo(processes, currentTime)) {
            PCB current = (PCB)processes.get(0);
            current.state = "运行";
            if (current.remainTime <= timeSlice) {
                current.cpuTime += current.remainTime;
                current.remainTime = 0;
                current.finishTime = currentTime + current.allTime;
                currentTime = current.finishTime;
                current.state = "结束";
                finishList.add(current);
                processes.remove(current);
            } else {
                current.cpuTime += timeSlice;
                current.remainTime -= timeSlice;
                currentTime += timeSlice;
                processes.remove(current);
                processes.add(current);
            }
        }

        printMetrics(finishList);
    }

    private static void printProcessInfo(List<PCB> processes, int currentTime) {
        System.out.println("当前时间: " + currentTime);
        System.out.println("进程ID\t优先级\t已用CPU时间\t总需时间\t剩余时间\t状态");
        Iterator var2 = processes.iterator();

        while(var2.hasNext()) {
            PCB p = (PCB)var2.next();
            System.out.println(p.id + "\t\t" + p.priority + "\t\t" + p.cpuTime + "\t\t" + p.allTime + "\t\t" + p.remainTime + "\t\t" + p.state);
        }

    }

    private static void printMetrics(List<PCB> processes) {
        double totalTurnaroundTime = 0.0;

        double turnaroundTime;
        for(Iterator var3 = processes.iterator(); var3.hasNext(); totalTurnaroundTime += turnaroundTime) {
            PCB p = (PCB)var3.next();
            turnaroundTime = (double)p.finishTime;
        }

        double averageTurnaroundTime = totalTurnaroundTime / (double)processes.size();
        System.out.println("平均周转时间: " + averageTurnaroundTime);
    }
}
